/*
    Copyright (C) 2011  Hugo Arregui, FuDePAN

    This file is part of the FuDePAN Extensible Cache

    Feca is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Feca is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Feca.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef FECA_CACHE_H
#define FECA_CACHE_H

template<class A, class B>
struct CreateLoader
{
    static A* create(B* _loader)
    {
        return new A(_loader);
    }
};

template<class A>
struct CreateLoader<A, A>
{
    static A* create(A* _loader)
    {
        return _loader;
    }
};

//TODO[C++0x]: see Cache [C++0x] comment
template<class T>
struct FriendMaker
{
    typedef T Type;
};

template <template <class, class> class StoragePolicy, template <class, class > class LoadingPolicy, class CacheOrLoaderType>
class Cache : public StoragePolicy<typename CacheOrLoaderType::Key, typename CacheOrLoaderType::CacheableObject>
{
public:
    typedef typename LoadingPolicy<Cache<StoragePolicy, LoadingPolicy, CacheOrLoaderType>, CacheOrLoaderType >::Type CacheLoadingPolicy;
    typedef typename CacheOrLoaderType::Key Key;
    typedef typename CacheOrLoaderType::CacheableObject CacheableObject;
    typedef typename CacheOrLoaderType::Loader Loader;

    //TODO[C++0x]: esto deberia ser directo
#if (MILI_COMPILER == MILI_COMPILER_VS)
    friend typename FriendMaker<CacheLoadingPolicy>::Type;
#else
    friend class FriendMaker<CacheLoadingPolicy>::Type;
#endif

    Cache(Loader* _loader) :
        loader(CreateLoader<CacheOrLoaderType, Loader>::create(_loader)),
        loadingPolicy(CacheLoadingPolicy(*this))
    {}
    ~Cache()
    {
        delete loader;
    }
    bool load_next(Key& i, CacheableObject& o)
    {
        return loader->load_next(i, o);
    }
    bool load(Key id, CacheableObject& o)
    {
        return loader->load(id, o);
    }
    Key next_key(Key k) const
    {
        return loader->next_key(k);
    }
    Key next_key() const
    {
        return loader->next_key();
    }
    CacheableObject createEmptyObject(Key k)
    {
        return loader->createEmptyObject(k);
    }
    CacheableObject* get(Key id)
    {
        loadingPolicy.onKeyRequested(id);
        return StoragePolicy<Key, CacheableObject>::get(id);
    }
private:
    CacheOrLoaderType* const loader;
    CacheLoadingPolicy loadingPolicy;
};

#endif
